package com.jacky.concurrent;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by jacky on 2018/2/11.
 */
public class MyCyclicBarrier {
    private int count;
    private int parties;
    private  Runnable barrierAction;

    private final ReentrantLock lock = new ReentrantLock();

    private final Condition condition = lock.newCondition();


    public MyCyclicBarrier(int parties,Runnable barrierAction){
        if (parties <=0){
            throw new IllegalArgumentException();
        }
        this.parties = parties;
        this.count = parties;
        this.barrierAction = barrierAction;
    }
    public  int await() throws InterruptedException,BrokenBarrierException {
        lock.lock();
        try {
            int index = --count;
            if (index ==0){
              if (null == barrierAction){
                  barrierAction.run();
              }
                condition.signalAll();
               return  index;
            }
            for (;;){
                 condition.await();
                return index;
            }
        }finally {
            lock.unlock();
        }
    }
}
